import 'package:flutter/material.dart';
import 'package:flutter_svg/svg.dart';
import 'package:get/get.dart';
import 'package:ducafe_ui_core/ducafe_ui_core.dart';
import 'package:go_router/go_router.dart';

import '../../common/index.dart';
import 'index.dart';

class OthersPage extends GetView<OthersController> {
  const OthersPage({super.key});

  @override
  Widget build(BuildContext context) {
    // 尝试从GoRouter获取额外数据
    final routerExtra = GoRouterState.of(context).extra;

    // 如果是用户模型数据，直接传递给控制器
    if (routerExtra != null && routerExtra is UserModel) {
      WidgetsBinding.instance.addPostFrameCallback((_) {
        Get.find<OthersController>().set_user_data(routerExtra);
      });
    }

    return GetBuilder<OthersController>(
      init: OthersController(),
      id: "others",
      builder: (_) {
        return Scaffold(
          body: Container(
            width: double.infinity,
            height: double.infinity,
            decoration: BoxDecoration(
              image: DecorationImage(
                image: AssetImage(AssetsImages.mineBg),
                fit: BoxFit.cover,
              ),
            ),
            child: SafeArea(top: false, bottom: false, child: _buildView()),
          ),
        );
      },
    );
  }

  // 主视图
  Widget _buildView() {
    return Stack(
      children: [
        GetBuilder<OthersController>(
          id: "main_view",
          builder: (_) {
            // 等待初始化完成
            if (!controller.is_initialized.value) {
              return Center(child: CircularProgressIndicator());
            }

            return Column(
              children: [
                SizedBox(height: 60.h),
                // 返回按钮
                Row(
                  children: [
                    SizedBox(width: 24.w),
                    GestureDetector(
                      onTap: () => RouteUtil.pop(),
                      child: Container(
                        height: 40.h,
                        width: 40.w,
                        padding: EdgeInsets.all(10.r),
                        decoration: BoxDecoration(
                          color: Color(0xFFCDFF5F),
                          borderRadius: BorderRadius.circular(10.r),
                        ),
                        child: SvgPicture.asset(
                          AssetsImages.back,
                          width: 20.w,
                          height: 20.h,
                        ),
                      ),
                    ),
                    Spacer(),
                  ],
                ),
                SizedBox(height: 55.h),

                // 用户信息区域
                _build_user_info_section(),
                SizedBox(height: 20.h),

                // 操作按钮
                _build_action_buttons(),
                SizedBox(height: 16.h),

                // 植物展示部分
                Expanded(
                  child: Container(
                    decoration: BoxDecoration(
                      color: Colors.black,
                      borderRadius: BorderRadius.only(
                        topLeft: Radius.circular(40.r),
                        topRight: Radius.circular(40.r),
                      ),
                    ),
                    child: Column(
                      children: [
                        SizedBox(height: 16.h),
                        Expanded(child: _build_plants_grid()),
                      ],
                    ),
                  ),
                ),
              ],
            );
          },
        ),

        // 礼物弹窗
        GetBuilder<OthersController>(
          id: "gift_dialog",
          builder: (_) {
            return _build_gift_dialog();
          },
        ),
      ],
    );
  }

  // 礼物弹窗
  Widget _build_gift_dialog() {
    return GetBuilder<OthersController>(
      id: "gift_dialog",
      builder: (_) {
        // 根据控制器的状态显示或隐藏弹窗
        if (!controller.is_gift_dialog_visible.value) {
          return const SizedBox.shrink();
        }

        // 获取当前选中的礼物
        final selectedGift =
            controller.gift_list[controller.selected_gift_index.value];

        return GestureDetector(
          onTap: () => controller.close_gift_dialog(), // 点击遮罩层关闭弹窗
          child: Container(
            width: double.infinity,
            height: double.infinity,
            color: Colors.black54,
            child: Center(
              child: GestureDetector(
                onTap: () {}, // 阻止点击内容区域时关闭弹窗
                child: AspectRatio(
                  aspectRatio: 458 / 309,
                  child: Container(
                    width: 458.w,
                    height: 309.h,
                    decoration: BoxDecoration(
                      image: DecorationImage(
                        image: AssetImage(AssetsImages.giftBg),
                        fit: BoxFit.contain,
                      ),
                    ),
                    child: Stack(
                      children: [
                        // 关闭按钮
                        Positioned(
                          top: 57.h,
                          right: 85.w,
                          child: GestureDetector(
                            onTap: () =>
                                controller.close_gift_dialog(), // 点击关闭按钮关闭弹窗
                            child: Container(
                              width: 28.w,
                              height: 28.h,
                              decoration: ShapeDecoration(
                                color: const Color(0xFFCDFF5F),
                                shape: OvalBorder(),
                              ),
                              child: Center(
                                child: Text(
                                  '✕',
                                  style: TextStyle(
                                    color: Colors.black,
                                    fontSize: 16.sp,
                                    fontWeight: FontWeight.w900,
                                    height: 1,
                                  ),
                                ),
                              ),
                            ),
                          ),
                        ),

                        // 价格 - Olii Pro
                        if (selectedGift['type'] == '非消耗品')
                          Positioned(
                            top: 70.h,
                            left: 155.w,
                            child: Text(
                              selectedGift['price'] as String,
                              textAlign: TextAlign.center,
                              style: TextStyle(
                                color: Colors.black,
                                fontSize: 20.sp,
                                fontWeight: FontWeight.w900,
                              ),
                            ),
                          ),

                        // 价格 - 其他礼物
                        if (selectedGift['type'] == '消耗品')
                          Positioned(
                            top: 80.h,
                            left: 140.w,
                            child: Text(
                              selectedGift['price'] as String,
                              textAlign: TextAlign.center,
                              style: TextStyle(
                                color: Colors.black,
                                fontSize: 36.sp,
                                fontWeight: FontWeight.w900,
                              ),
                            ),
                          ),

                        // 提示文字
                        if (selectedGift['name'] == 'Olii Pro')
                          Positioned(
                            top: 100.h,
                            left: 165.w,
                            child: SizedBox(
                              width: 100.w,
                              child: Text(
                                'Can only be purchased once',
                                style: TextStyle(
                                  color: const Color(0x2345204C),
                                  fontSize: 11.sp,
                                  fontWeight: FontWeight.w300,
                                  height: 1,
                                ),
                              ),
                            ),
                          ),

                        // 赠送按钮
                        Positioned(
                          top: 95.h,
                          right: 90.w,
                          child: AnimatedBuilder(
                            animation: controller.giveButtonAnimation,
                            builder: (context, child) {
                              return Transform.scale(
                                scale: controller.giveButtonAnimation.value,
                                child: GestureDetector(
                                  onTap: () => controller.give_gift(),
                                  child: Container(
                                    width: 70.w,
                                    padding: EdgeInsets.symmetric(
                                      vertical: 2.h,
                                    ),
                                    decoration: ShapeDecoration(
                                      color: Colors.black,
                                      shape: RoundedRectangleBorder(
                                        side: BorderSide(width: 1.w),
                                        borderRadius: BorderRadius.circular(
                                          10.r,
                                        ),
                                      ),
                                      shadows: [
                                        BoxShadow(
                                          color: Color(
                                            0xFFCDFF5F,
                                          ).withOpacity(0.5),
                                          blurRadius: 8,
                                          spreadRadius:
                                              controller
                                                      .giveButtonAnimation
                                                      .value ==
                                                  1.0
                                              ? 0
                                              : 2,
                                        ),
                                      ],
                                    ),
                                    child: Row(
                                      mainAxisSize: MainAxisSize.min,
                                      mainAxisAlignment:
                                          MainAxisAlignment.center,
                                      crossAxisAlignment:
                                          CrossAxisAlignment.center,
                                      spacing: 10,
                                      children: [
                                        Text(
                                          'Give Away',
                                          textAlign: TextAlign.center,
                                          style: TextStyle(
                                            color: Colors.white,
                                            fontSize: 10.sp,
                                            fontWeight: FontWeight.w700,
                                          ),
                                        ),
                                      ],
                                    ),
                                  ),
                                ),
                              );
                            },
                          ),
                        ),

                        // 礼物图片
                        Positioned(
                          top: 70.h,
                          left: 87.w,
                          child: Image.asset(
                            AssetsImages.giftFlower,
                            width: 54.w,
                            height: 54.h,
                          ),
                        ),

                        // 礼物列表 - 底部横向滚动
                        Positioned(
                          bottom: 10.h,
                          left: 72.w,
                          right: 78.w,
                          child: SizedBox(
                            height: 120.h,
                            child: SingleChildScrollView(
                              scrollDirection: Axis.horizontal,
                              child: Row(
                                children: List.generate(
                                  controller.gift_list.length,
                                  (index) => _buildGiftCard(index),
                                ),
                              ),
                            ),
                          ),
                        ),
                      ],
                    ),
                  ),
                ),
              ),
            ),
          ),
        );
      },
    );
  }

  // 礼物卡片
  Widget _buildGiftCard(int index) {
    final gift = controller.gift_list[index];
    final isSelected = controller.selected_gift_index.value == index;

    return GestureDetector(
      onTap: () => controller.select_gift(index),
      child: TweenAnimationBuilder<double>(
        duration: Duration(milliseconds: 200),
        tween: Tween<double>(begin: 1.0, end: isSelected ? 1.05 : 1.0),
        builder: (context, value, child) {
          return Transform.scale(scale: value, child: child!);
        },
        child: Padding(
          padding: EdgeInsets.symmetric(horizontal: 2.w),
          child: Column(
            mainAxisSize: MainAxisSize.min,
            children: [
              // 上半部分
              Container(
                width: 75.w,
                height: 96.h,
                padding: EdgeInsets.only(top: 8.r, bottom: 2.h),
                decoration: BoxDecoration(
                  color: Color(0xFF252525),
                  borderRadius: BorderRadius.only(
                    topLeft: Radius.circular(15.r),
                    topRight: Radius.circular(15.r),
                  ),
                  border: isSelected
                      ? Border(
                          top: BorderSide(
                            color: Color(0xFFCDFF5F),
                            width: 1.5.w,
                          ),
                          left: BorderSide(
                            color: Color(0xFFCDFF5F),
                            width: 1.5.w,
                          ),
                          right: BorderSide(
                            color: Color(0xFFCDFF5F),
                            width: 1.5.w,
                          ),
                        )
                      : null,
                ),
                child: Column(
                  children: [
                    // 礼物图片
                    Image.asset(
                      AssetsImages.giftFlower1,
                      width: 45.w,
                      height: 45.h,
                      fit: BoxFit.contain,
                    ),

                    SizedBox(height: 2.h),

                    // 礼物名称
                    Text(
                      gift['name'] as String,
                      textAlign: TextAlign.center,
                      style: TextStyle(
                        color: Color(0xFFCDFF5F),
                        fontSize: 12.sp,
                        fontWeight: FontWeight.w900,
                        textBaseline: TextBaseline.alphabetic,
                        height: 1.2,
                      ),
                      maxLines: 1,
                      overflow: TextOverflow.ellipsis,
                    ),
                    SizedBox(height: 2.h),

                    // 礼物价格
                    Text(
                      gift['price'] as String,
                      textAlign: TextAlign.center,
                      style: TextStyle(
                        color: Color(0xFFCDFF5F),
                        fontSize: 14.sp,
                        fontWeight: FontWeight.w900,
                        height: 1.2,
                      ),
                    ),
                  ],
                ),
              ),

              // 下半部分按钮
              AnimatedContainer(
                duration: Duration(milliseconds: 150),
                curve: Curves.easeInOut,
                width: 75.w,
                height: 24.h,
                decoration: BoxDecoration(
                  color: isSelected ? Color(0xFFCDFF5F) : Color(0xFF7AA618),
                  borderRadius: BorderRadius.only(
                    bottomLeft: Radius.circular(15.r),
                    bottomRight: Radius.circular(15.r),
                  ),
                  boxShadow: isSelected
                      ? [
                          BoxShadow(
                            color: Color(0xFFCDFF5F).withOpacity(0.4),
                            blurRadius: 6,
                            spreadRadius: 1,
                          ),
                        ]
                      : [],
                ),
                child: Center(
                  child: Text(
                    'Give Away',
                    textAlign: TextAlign.center,
                    style: TextStyle(
                      color: isSelected ? Colors.black : Colors.white,
                      fontSize: 12.sp,
                      fontWeight: FontWeight.w400,
                      fontFamily: "PingFang SC",
                      height: 1,
                      textBaseline: TextBaseline.alphabetic,
                    ),
                  ),
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }

  // 用户信息部分
  Widget _build_user_info_section() {
    final user_data = controller.user_data;

    return Container(
      padding: EdgeInsets.symmetric(horizontal: 28.w),
      child: Row(
        children: [
          Container(
            decoration: BoxDecoration(
              shape: BoxShape.circle,
              border: Border.all(color: Colors.white, width: 4.w),
            ),
            child: CircleAvatar(
              backgroundImage: ImagePath().get_post_image(
                user_data['avatar']?.toString() ?? '',
              ),
              radius: 48.r,
            ),
          ),
          SizedBox(width: 16.w),
          Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Obx(() {
                // 限制用户名最多显示12个字符
                String displayName =
                    controller.user_data['name']?.toUpperCase() ??
                    'USERNAME';
                if (displayName.length > 12) {
                  displayName = displayName.substring(0, 12);
                }

                return Row(
                  children: [
                    // 用户名和VIP标志在同一行
                    Row(
                      mainAxisSize: MainAxisSize.min,
                      children: [
                        Text(
                          displayName,
                          style: TextStyle(
                            color: Colors.white,
                            fontSize: 18.sp,
                            fontWeight: FontWeight.bold,
                          ),
                        ),
                        // VIP标志紧跟用户名后面
                        if (user_data['is_vip'] == true)
                          Container(
                            margin: EdgeInsets.only(left: 6.w),
                            padding: EdgeInsets.symmetric(
                              horizontal: 6.w,
                              vertical: 3.h,
                            ),
                            decoration: BoxDecoration(
                              gradient: LinearGradient(
                                colors: [Color(0xFF1E2E3D), Color(0xFF273747)],
                                begin: Alignment.topLeft,
                                end: Alignment.bottomRight,
                              ),
                              borderRadius: BorderRadius.circular(8.r),
                              boxShadow: [
                                BoxShadow(
                                  color: Colors.black.withOpacity(0.3),
                                  blurRadius: 3,
                                  offset: Offset(0, 1),
                                ),
                              ],
                              border: Border.all(
                                color: Color(0xFF4CAF50),
                                width: 1.w,
                              ),
                            ),
                            child: Row(
                              mainAxisSize: MainAxisSize.min,
                              children: [
                                Icon(
                                  Icons.verified_user,
                                  color: Color(0xFF4CAF50),
                                  size: 8.sp,
                                ),
                                SizedBox(width: 3.w),
                                Text(
                                  'VIP',
                                  style: TextStyle(
                                    color: Color(0xFF4CAF50),
                                    fontSize: 9.sp,
                                    fontWeight: FontWeight.w900,
                                    letterSpacing: 0.5,
                                  ),
                                ),
                              ],
                            ),
                          ),

                        if (user_data['is_vip'] == false)
                          Text(
                            '🌼',
                            style: TextStyle(
                              color: Colors.white,
                              fontSize: 18.sp,
                            ),
                          ),
                      ],
                    ),
                  ],
                );
              }),
              SizedBox(height: 4.h),
              SizedBox(
                width: 180.w,
                child: Text(
                  user_data['introduction']?.toString() ?? '',
                  style: TextStyle(color: Colors.white70, fontSize: 12.sp),
                  maxLines: 2,
                  overflow: TextOverflow.ellipsis,
                ),
              ),
            ],
          ),
        ],
      ),
    );
  }

  // 操作按钮
  Widget _build_action_buttons() {
    return Padding(
      padding: EdgeInsets.symmetric(horizontal: 28.w),
      child: Row(
        children: [
          Expanded(
            child: ElevatedButton.icon(
              icon: SvgPicture.asset(
                AssetsImages.cardGift,
                width: 20.w,
                height: 20.h,
                colorFilter: ColorFilter.mode(Colors.white, BlendMode.srcIn),
              ),
              label: Text(
                'Gift Giving',
                style: TextStyle(
                  color: Colors.white,
                  fontSize: 14.sp,
                  fontWeight: FontWeight.w700,
                ),
              ),
              onPressed: () => controller.send_gift(),
              style: ElevatedButton.styleFrom(
                backgroundColor: Colors.black.withOpacity(0.6),
                foregroundColor: Colors.white,
                elevation: 5,
                shadowColor: Colors.black38,
                shape: RoundedRectangleBorder(
                  borderRadius: BorderRadius.circular(20.r),
                  side: BorderSide(color: Color(0xFFCDFF5F), width: 1.5.w),
                ),
                padding: EdgeInsets.symmetric(vertical: 14.h),
              ),
            ),
          ),
          SizedBox(width: 16.w),
          Expanded(
            child: ElevatedButton.icon(
              icon: SvgPicture.asset(
                AssetsImages.hi,
                width: 20.w,
                height: 20.h,
                colorFilter: ColorFilter.mode(Colors.white, BlendMode.srcIn),
              ),
              label: Text(
                'Send a message',
                style: TextStyle(
                  color: Colors.white,
                  fontSize: 14.sp,
                  fontWeight: FontWeight.w700,
                ),
              ),
              onPressed: () => controller.send_message(),
              style: ElevatedButton.styleFrom(
                backgroundColor: Colors.black.withOpacity(0.6),
                foregroundColor: Colors.white,
                elevation: 5,
                shadowColor: Colors.black38,
                shape: RoundedRectangleBorder(
                  borderRadius: BorderRadius.circular(20.r),
                  side: BorderSide(color: Color(0xFFCDFF5F), width: 1.5.w),
                ),
                padding: EdgeInsets.symmetric(vertical: 14.h),
              ),
            ),
          ),
        ],
      ),
    );
  }

  // 植物网格
  Widget _build_plants_grid() {
    final plants = controller.user_data['plants'] as List? ?? [];

    if (plants.isEmpty) {
      return Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Icon(
              Icons.eco_outlined,
              color: Colors.white.withOpacity(0.6),
              size: 60.r,
            ),
            SizedBox(height: 16.h),
            Text(
              "No plants to display yet",
              style: TextStyle(
                color: Colors.white.withOpacity(0.8),
                fontSize: 16.sp,
                fontWeight: FontWeight.w500,
              ),
            ),
            SizedBox(height: 8.h),
            Text(
              "This user hasn't shared any plants",
              style: TextStyle(
                color: Colors.white.withOpacity(0.6),
                fontSize: 14.sp,
              ),
            ),
          ],
        ),
      );
    }

    return Padding(
      padding: EdgeInsets.symmetric(horizontal: 16.w),
      child: GridView.builder(
        gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
          crossAxisCount: 2,
          crossAxisSpacing: 12.w,
          mainAxisSpacing: 12.h,
          childAspectRatio: 0.9,
        ),
        itemCount: plants.length,
        itemBuilder: (context, index) {
          final plant = plants[index] as Map<String, dynamic>? ?? {};
          final isLiked = plant['liked'] as bool? ?? false;

          // Handle different image formats and extract first image
          String firstImage = 'assets/images/default_plant.png';
          final plantImage = plant['image'];

          if (plantImage is List && plantImage.isNotEmpty) {
            firstImage = plantImage.first.toString();
          } else if (plantImage is String) {
            if (plantImage.contains(',')) {
              // Handle comma-separated image paths
              firstImage = plantImage.split(',').first.trim();
            } else {
              firstImage = plantImage;
            }
          }

          return GestureDetector(
            onTap: () => controller.navigate_to_plant_detail(plant),
            child: Container(
              decoration: BoxDecoration(
                borderRadius: BorderRadius.circular(16.r),
                image: DecorationImage(
                  image: ImagePath().get_post_image(firstImage),
                  fit: BoxFit.cover,
                ),
              ),
              child: Stack(
                children: [
                  // 底部渐变
                  Positioned(
                    bottom: 0,
                    left: 0,
                    right: 0,
                    child: Container(
                      height: 60.h,
                      decoration: BoxDecoration(
                        borderRadius: BorderRadius.only(
                          bottomLeft: Radius.circular(16.r),
                          bottomRight: Radius.circular(16.r),
                        ),
                        gradient: LinearGradient(
                          begin: Alignment.topCenter,
                          end: Alignment.bottomCenter,
                          colors: [
                            Colors.transparent,
                            Colors.black.withOpacity(0.7),
                          ],
                        ),
                      ),
                    ),
                  ),

                  // 用户头像和名称
                  Positioned(
                    bottom: 8.h,
                    left: 8.w,
                    child: Row(
                      children: [
                        CircleAvatar(
                          backgroundImage: ImagePath().get_post_image(
                            controller.user_data['avatar']?.toString() ?? '',
                          ),
                          radius: 12.r,
                        ),
                        SizedBox(width: 4.w),
                        Text(
                          controller.user_data['name']?.toString() ?? 'User',
                          style: TextStyle(
                            color: Colors.white,
                            fontSize: 12.sp,
                            fontWeight: FontWeight.w500,
                          ),
                        ),
                      ],
                    ),
                  ),

                  // 收藏按钮（仅显示，不提供功能）
                  Positioned(
                    bottom: 8.h,
                    right: 8.w,
                    child: Container(
                      width: 32.w,
                      height: 32.h,
                      decoration: BoxDecoration(
                        color: Colors.black.withOpacity(0.5),
                        shape: BoxShape.circle,
                      ),
                      child: Icon(
                        isLiked ? Icons.favorite : Icons.favorite_border,
                        color: isLiked ? Colors.red : Colors.white,
                        size: 18.w,
                      ),
                    ),
                  ),
                ],
              ),
            ),
          );
        },
      ),
    );
  }
}
